package plus.H5D3B5016;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import plus.H5D3B5016.bean.BtcLogEntity;
import plus.H5D3B5016.bean.WTForm;
import plus.H5D3B5016.event.EventType;
import plus.H5D3B5016.event.MyEvent;
import plus.H5D3B5016.event.PriceEvent;
import plus.H5D3B5016.utils.ACache;
import plus.H5D3B5016.view.RecyclerAdapter;
import plus.H5D3B5016.view.TxDialog;

@ContentView(R.layout.activity_xiadan2)
public class XiaDan2Activity extends BaseActivity {


    @ViewInject(R.id.left)
    ImageView left;
    @ViewInject(R.id.datetext)
    TextView  datetext;
    @ViewInject(R.id.jiage)
    TextView  jiage;

    @ViewInject(R.id.tpzf)
    TextView  tpzf;
    @ViewInject(R.id.zf)
    TextView  zf;



    @ViewInject(R.id.to4)
    Button to4;


    @ViewInject(R.id.but1)
    TextView  but1;
    @ViewInject(R.id.but2)
    TextView  but2;

    @ViewInject(R.id.gg1)
    TextView  gg1;
    @ViewInject(R.id.gg2)
    TextView  gg2;

    @ViewInject(R.id.m1)
    TextView  m1;
    @ViewInject(R.id.m2)
    TextView  m2;
    @ViewInject(R.id.m3)
    TextView  m3;
    @ViewInject(R.id.m4)
    TextView  m4;
    @ViewInject(R.id.m5)
    TextView  m5;
    @ViewInject(R.id.m6)
    TextView  m6;



    @ViewInject(R.id.recycler_view)
    RecyclerView recycler_view;


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private double myclose;//当前价格
    private double myopen;// 开盘价格


    RecyclerAdapter mRecyclerAdapter;
    List<BtcLogEntity> ccList=new ArrayList<>();//持仓


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        to4.setTag(true);
        to4.setText("停止下单");
        to4.setBackground(getResources().getDrawable(R.drawable.ic_zd));

        je=10000;
        ldje();


        try{

            mRecyclerAdapter = new RecyclerAdapter<BtcLogEntity>(this, ccList, R.layout.item_cc) {
                @Override
                public void convert(RecyclerViewHolder helper, int position, BtcLogEntity item) {
                    //helper.setText(R.id.symbolName,item.getSymbolName());
                    if(null==btcLog&&null==item.getOutDate()){
                        btcLog=item;
                    }
                    LinearLayout myitem=helper.getView(R.id.myitem);
                    myitem.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            pingcang(true);

                            Vibrator vibrator = (Vibrator)XiaDan2Activity.this.getSystemService(XiaDan2Activity.this.VIBRATOR_SERVICE);
                            vibrator.vibrate(300);

                            show("自动平仓");
                            return true;
                        }
                    });


                    helper.setText(R.id.direction,(item.getDirection().equals("buy")?"做多":"做空"));
                    helper.setText(R.id.inTime,""+sdf.format(item.getInDate()));
                    helper.setText(R.id.inAmount,"本金:"+item.getAmount());
                    helper.setText(R.id.feeAmount,"手续费:"+item.getFactorge());
                    helper.setText(R.id.rate,"杠杆:"+item.getRate()+"X");
                    helper.setText(R.id.inPrice,""+item.getInPrice());

                    if(item.getDirection().equals("buy")){
                        ((TextView)helper.getView(R.id.direction)).setTextColor(getResources().getColor(R.color.zd));
                    }else{
                        ((TextView)helper.getView(R.id.direction)).setTextColor(getResources().getColor(R.color.zk));
                    }

                    double outPrice=myclose;
                    if(null!=item.getOutPrice()){
                        outPrice=item.getOutPrice();
                    }

                    if(null!=item.getOutDate()){
                        helper.setText(R.id.outPrice,""+item.getOutPrice());
                        helper.setText(R.id.outTime,"平仓时间:"+sdf.format(item.getOutDate()));
                    }else{
                        helper.setText(R.id.outPrice,"暂无");
                        helper.setText(R.id.outTime,"平仓时间:暂无");
                    }

                    if((outPrice-item.getInPrice())>0){
                        ((TextView)helper.getView(R.id.outAmount)).setTextColor(getResources().getColor(R.color.zd));
                        ((TextView)helper.getView(R.id.outPrice)).setTextColor(getResources().getColor(R.color.zd));
                        helper.setText(R.id.outAmount,String.format("%.2f",(outPrice-item.getInPrice())/30*item.getAmount()));
                    }else if((outPrice-item.getInPrice())<0){
                        ((TextView)helper.getView(R.id.outAmount)).setTextColor(getResources().getColor(R.color.zk));
                        ((TextView)helper.getView(R.id.outPrice)).setTextColor(getResources().getColor(R.color.zk));
                        helper.setText(R.id.outAmount,String.format("%.2f",(outPrice-item.getInPrice())/30*item.getAmount()) );
                    }else{
                        ((TextView)helper.getView(R.id.outAmount)).setTextColor(getResources().getColor(R.color.zh));
                        ((TextView)helper.getView(R.id.outPrice)).setTextColor(getResources().getColor(R.color.zh));
                        helper.setText(R.id.outAmount,""+(item.getInPrice()));
                    }
                }
            };
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recycler_view.setLayoutManager(layoutManager);
            recycler_view.setAdapter(mRecyclerAdapter);


            queryList();

        }catch (Exception e){}

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public  void onEvent(PriceEvent priceEvent){
        try{

            String txst=ACache.get(getApplicationContext()).getAsString("txst");
            int st=30;
            if(null!=txst){
                st=Integer.valueOf(txst);
            }

            if(priceEvent.getZf()>0){
                zf.setTextColor(getResources().getColor(R.color.zd));
            }else{
                zf.setTextColor(getResources().getColor(R.color.zk));
            }
            tpzf.setText(st+"秒内涨幅:");
            zf.setText(String.format("%.2f", priceEvent.getZf()));
        }catch (Exception e){}
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public  void onEvent(MyEvent myEvent){
        if(myEvent.getType()!= EventType.READ){
            return;
        }

        JSONObject jo=(JSONObject)myEvent.getObj();
        try {
            //Log.d("xxxx",jo.toString());

            double close=jo.getDouble("close");// 最新价
            double open=jo.getDouble("open");// 今日开盘价格
            myopen=open;

            Long timestamp=jo.getLong("timestamp");// timestamp
            myclose=close;
            //mydate=new Date(timestamp);
            //datetext.setText("moon send 时间:"+sdf.format(mydate));
            jiage.setText("BTC/USDT指数:"+close);
            if(myclose>myopen){
                jiage.setTextColor(getResources().getColor(R.color.zd));
            }else{
                jiage.setTextColor(getResources().getColor(R.color.zk));
            }

            try{
                for (BtcLogEntity btcLogEntity:ccList){
                    if(null==btcLogEntity.getOutDate()){
                        btcLogEntity.setOutPrice(myclose);
                    }
                }
                mRecyclerAdapter.notifyDataSetChanged();
            }catch (Exception ee){}

        }catch (Exception e){}
    }

    private void showCoverDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("关闭窗口将取消自动委托,是否关闭？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        builder.setNegativeButton("取消",null);
        builder.show();
    }



    @Event(value = {R.id.left,R.id.but1,R.id.but2,
            R.id.m1,R.id.m2,R.id.m3,R.id.m4,R.id.m5,R.id.m6,
            R.id.gg1,R.id.gg2,R.id.to4,R.id.to5,R.id.to6},type = View.OnClickListener.class)
    private void onclick(View view){
        switch (view.getId()){
            case R.id.left:
                showCoverDialog();
                break;
            case R.id.but1:
                fx=true;
                fx();
                break;
            case R.id.but2:
                fx=false;
                fx();
                break;
            case R.id.m1:
                je=100;
                ldje();
                break;
            case R.id.m2:
                je=500;
                ldje();
                break;
            case R.id.m3:
                je=1000;
                ldje();
                break;
            case R.id.m4:
                je=2000;
                ldje();
                break;
            case R.id.m5:
                je=5000;
                ldje();
                break;
            case R.id.m6:
                je=10000;
                ldje();
                break;
            case R.id.gg1:
                gg=25;
                ldgg();
                break;
            case R.id.gg2:
                gg=50;
                ldgg();
                break;
            case R.id.to4:
                boolean isxd=(Boolean) to4.getTag();
                if(!isxd){
                    to4.setTag(true);
                    to4.setText("停止下单");
                    mHandler2.postDelayed(runnable2, 1000);
                    to4.setBackground(getResources().getDrawable(R.drawable.ic_zd));
                }else{
                    to4.setTag(false);
                    to4.setText("自动下单");
                    to4.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                }
                break;
            case R.id.to5:
                try {
                    app.db.delete(BtcLogEntity.class);
                    show("清除成功");
                    queryList();
                } catch (DbException e) {}
                break;
            case R.id.to6:
                TxDialog txDialog=new TxDialog(XiaDan2Activity.this,1);
                txDialog.show(getSupportFragmentManager(),"tx2");
                txDialog.setOnConfirmClickListener(new TxDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirm(int st, int et) {
                        ACache.get(XiaDan2Activity.this).put("txst2",""+st);
                        ACache.get(XiaDan2Activity.this).put("txet2",""+et);
                    }
                });
                break;
        }
    }



    boolean fx=true;
    /**
     * 做多
     */
    private void fx(){

        if(fx){
            but1.setBackground(getResources().getDrawable(R.drawable.ic_zd));
            but2.setBackground(getResources().getDrawable(R.drawable.ic_zh));
            but1.setTextColor(Color.WHITE);
            but2.setTextColor(Color.parseColor("#283043"));

        }else{
            but1.setBackground(getResources().getDrawable(R.drawable.ic_zh));
            but2.setBackground(getResources().getDrawable(R.drawable.ic_zk));
            but1.setTextColor(Color.parseColor("#283043"));
            but2.setTextColor(Color.WHITE);

        }

        ldje();
        ldgg();
    }




    int je=100;

    /**
     * 联动金额
     */
    private void ldje(){
        int fxres=0;
        if(fx){
            fxres=R.drawable.ic_zd;
        }else{
            fxres=R.drawable.ic_zk;
        }

        switch (je){
            case 100:
                m1.setBackground(getResources().getDrawable(fxres));
                m2.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m3.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m4.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m5.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m6.setBackground(getResources().getDrawable(R.drawable.ic_zh));



                m1.setTextColor(Color.parseColor("#283043"));
                m2.setTextColor(Color.parseColor("#283043"));
                m3.setTextColor(Color.parseColor("#283043"));
                m4.setTextColor(Color.parseColor("#283043"));
                m5.setTextColor(Color.parseColor("#283043"));
                m6.setTextColor(Color.parseColor("#283043"));
                m1.setTextColor(Color.WHITE);

                break;
            case 500:
                m1.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m2.setBackground(getResources().getDrawable(fxres));
                m3.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m4.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m5.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m6.setBackground(getResources().getDrawable(R.drawable.ic_zh));

                m1.setTextColor(Color.parseColor("#283043"));
                m2.setTextColor(Color.parseColor("#283043"));
                m3.setTextColor(Color.parseColor("#283043"));
                m4.setTextColor(Color.parseColor("#283043"));
                m5.setTextColor(Color.parseColor("#283043"));
                m6.setTextColor(Color.parseColor("#283043"));
                m2.setTextColor(Color.WHITE);
                break;
            case 1000:
                m1.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m2.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m3.setBackground(getResources().getDrawable(fxres));
                m4.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m5.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m6.setBackground(getResources().getDrawable(R.drawable.ic_zh));

                m1.setTextColor(Color.parseColor("#283043"));
                m2.setTextColor(Color.parseColor("#283043"));
                m3.setTextColor(Color.parseColor("#283043"));
                m4.setTextColor(Color.parseColor("#283043"));
                m5.setTextColor(Color.parseColor("#283043"));
                m6.setTextColor(Color.parseColor("#283043"));
                m3.setTextColor(Color.WHITE);

                break;
            case 2000:
                m1.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m2.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m3.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m4.setBackground(getResources().getDrawable(fxres));
                m5.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m6.setBackground(getResources().getDrawable(R.drawable.ic_zh));

                m1.setTextColor(Color.parseColor("#283043"));
                m2.setTextColor(Color.parseColor("#283043"));
                m3.setTextColor(Color.parseColor("#283043"));
                m4.setTextColor(Color.parseColor("#283043"));
                m5.setTextColor(Color.parseColor("#283043"));
                m6.setTextColor(Color.parseColor("#283043"));
                m4.setTextColor(Color.WHITE);
                break;
            case 5000:
                m1.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m2.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m3.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m4.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m5.setBackground(getResources().getDrawable(fxres));
                m6.setBackground(getResources().getDrawable(R.drawable.ic_zh));

                m1.setTextColor(Color.parseColor("#283043"));
                m2.setTextColor(Color.parseColor("#283043"));
                m3.setTextColor(Color.parseColor("#283043"));
                m4.setTextColor(Color.parseColor("#283043"));
                m5.setTextColor(Color.parseColor("#283043"));
                m6.setTextColor(Color.parseColor("#283043"));
                m5.setTextColor(Color.WHITE);

                break;
            case 10000:
                m1.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m2.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m3.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m4.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m5.setBackground(getResources().getDrawable(R.drawable.ic_zh));
                m6.setBackground(getResources().getDrawable(fxres));

                m1.setTextColor(Color.parseColor("#283043"));
                m2.setTextColor(Color.parseColor("#283043"));
                m3.setTextColor(Color.parseColor("#283043"));
                m4.setTextColor(Color.parseColor("#283043"));
                m5.setTextColor(Color.parseColor("#283043"));
                m6.setTextColor(Color.parseColor("#283043"));
                m6.setTextColor(Color.WHITE);
                break;
        }

    }

    int gg=50;
    private void ldgg(){
        int fxres=0;
        if(fx){
            fxres=R.drawable.ic_zd;
        }else{
            fxres=R.drawable.ic_zk;
        }

        if(gg==50){
            gg2.setBackground(getResources().getDrawable(fxres));
            gg1.setBackground(getResources().getDrawable(R.drawable.ic_zh));
            gg2.setTextColor(Color.WHITE);
            gg1.setTextColor(Color.parseColor("#283043"));
        }else{
            gg2.setBackground(getResources().getDrawable(R.drawable.ic_zh));
            gg1.setBackground(getResources().getDrawable(fxres));
            gg2.setTextColor(Color.parseColor("#283043"));
            gg1.setTextColor(Color.WHITE);
        }

    }





    boolean xdz=false;// 是否下单中

    BtcLogEntity btcLog=null;

    /**
     * 虚拟立即下单
     */
    private synchronized void xiadan2(){
        try {

            if(xdz){return;}

            if(!(Boolean)(to4.getTag())){
                return;
            }

            if(null!=btcLog){
                return;
            }
            String xcstr=ACache.get(XiaDan2Activity.this).getAsString("txst2");
            if(null==xcstr){
                xcstr="30";
            }

            if(Math.abs(Double.valueOf(zf.getText().toString()))<Double.valueOf(xcstr)){
                return;
            }


            xdz=true;

            WTForm wt2=new WTForm();
            wt2.setAmount(myclose);
            wt2.setRate(gg);
            wt2.setTxCurrency("btcusdt");

            wt2.setDirection((fx)?"buy":"sell");

            // 智能反下单
            if(Double.valueOf(zf.getText().toString())<0){
                wt2.setDirection("buy");
            }else{
                wt2.setDirection("sell");
            }

            wt2.setInAmount(je);

            show("开始下单");

            final Request request = new Request.Builder()
                    .url(Const.BASE_URL2 + "/btc/app/send")
                    .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),JSON.toJSONString(wt2)))
                    .build();

            post(request, new MyCall() {
                @Override
                public void onResponse(String response) {
                    if(null==response){
                        return;
                    }
                    try{
                        JSONObject jo=new JSONObject(response);
                        if(jo.getInt("code")!=0){
                            show(""+jo.getString("msg"));
                            return;
                        }

                        btcLog=JSON.parseObject(jo.getString("data"), BtcLogEntity.class);
                        if(null==btcLog){
                            show("返回数据有误");
                            return;
                        }
                        try {
                            btcLog.setState(0);
                            app.db.saveOrUpdate(btcLog);
                            queryList();
                        } catch (DbException e) {
                            show("保存错误");
                        }
                    }catch (Exception e){
                        Log.d("xxx",e.getMessage());
                    }finally {
                        xdz=false;
                    }
                }
            });

        }catch (Exception e){
            Log.d("xxx",e.getMessage());
        }
    }

    /**
     * 自动平仓
     */
    private synchronized void pingcang(boolean auto){
        try {


            if(!auto){
                String xcstr=ACache.get(XiaDan2Activity.this).getAsString("txet2");
                if(null==xcstr){
                    xcstr="30";
                }

                if(Math.abs(btcLog.getInPrice()-myclose)<Double.valueOf(xcstr)){
                    Log.d("xxx","浮动价格:"+Math.abs(btcLog.getInPrice()-myclose)+"  平仓价格:"+Double.valueOf(xcstr));
                    return;
                }
            }


            if(null==btcLog){
                return;
            }

            if(xdz){return;}
            xdz=true;

            show("开始平仓");

            RequestBody requestBody = new FormBody.Builder()
                    .add("id", btcLog.getId()+"")
                    .add("amount", myclose+"")
                    .build();

            Request request = new Request.Builder()
                    .url(Const.BASE_URL2 + "/btc/app/flat")
                    .post(requestBody)
                    .build();

            post(request, new MyCall() {
                @Override
                public void onResponse(String response) {
                    if(null==response){
                        return;
                    }

                    try{
                        JSONObject jo=new JSONObject(response);
                        if(jo.getInt("code")!=0){
                            show(""+jo.getString("msg"));
                            return;
                        }

                        btcLog=JSON.parseObject(jo.getString("data"), BtcLogEntity.class);
                        if(null==btcLog){
                            show("返回数据有误");
                            return;
                        }

                        try {
                            btcLog.setState(1);
                            app.db.update(btcLog);
                            btcLog=null;

                            queryList();
                        } catch (DbException e) {
                            show("保存错误");
                        }
                    }catch (Exception e){
                        Log.d("xxx",e.getMessage());
                    }finally {
                        xdz=false;
                    }
                }
            });

        }catch (Exception e){
        }
    }




    boolean auto=false;
    private void queryList(){
        try{
            ccList.clear();
            List<BtcLogEntity> btcList=app.db.selector(BtcLogEntity.class).where("1","=","1").orderBy("id",true).findAll();
            ccList.addAll(btcList);
            mRecyclerAdapter.notifyDataSetChanged();

            if(!auto){
                auto=true;
                mHandler2.postDelayed(runnable2, 5000);
            }
        }catch (Exception e){}
    }




    /**
     * 处理限价委托
     */
    private Handler mHandler2 = new Handler();
    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            try{
                xiadan2();
                pingcang(false);
            }catch (Exception e){}
            mHandler2.postDelayed(this, 1000);
        }
    };






}
